// ============================================================================
// JigVector
// The standard vector class supplies a way of allocating a dynamic array
// of objects, which is very nice. This class just extends the vector class
// slightly to provide access to the data in a way that suites Jiggle.
//
// CLH April-June 1998
// ============================================================================

package com.chrishobson.jiggle;

import java.util.Vector;

public class JigVector extends Vector<Object> {

  // ==========================================================================
  // Initialise to hold 8 items. 8 players is a sensible number
  // ==========================================================================
  public JigVector() {
    super(8);
  }

  // ==========================================================================
  // Adds a new object to the vector in the first available
  // slot. The slot that the object is stored in is returned.
  // ==========================================================================
  public int addObj(Object obj) {
    int id;
    int num = size();
    // Loop hoping to find an empty slot in the currently used slots.
    for(id = 0; id < num; ++id) {
      if(elementAt(id) == null) {
	      break;
      }
    }
    // Set either in a current slot or by growing if loop terminate normally
    set(obj,id);

    return id;
  }

  // ==========================================================================
  // Set the given slot to NULL
  // ==========================================================================
  void set_null(int id) {
    set(null,id);
  }

  // ==========================================================================
  // Sets the item at id increasing the vectors size if necessary.
  // ==========================================================================
  void set(Object obj, int id) {
    // If this id is >= size of the vector then the vector
    // must grow to allow the item to be safely set.
    if(id >= size()) {
      setSize(id+1);
    }
    setElementAt(obj,id);
  }

  // ==========================================================================
  // Get the object at the spefied index (id), return null if out of bounds.
  // ==========================================================================
  public Object getObj(int id) {
    Object obj = null;
    if(id < size()) {
      obj = elementAt(id);
    }
    return obj;
  }
}
